<template>
  <div>
    <div class="videoWrap">
      <div class="user" v-for="item in listClients" @click="event(item)">
        {{ item }}
      </div>
      <div class="item">
        <video
          style="width: 100%; height: 100%"
          ref="localPreview"
          autoplay
        ></video>
      </div>
      <div class="item">
        <video
          style="width: 100%; height: 100%"
          ref="remotePreview"
          muted
          controls
          autoplay
        ></video>
      </div>
    </div>
  </div>
</template>

<script>
import socket from "@/plugins/socketIO";

export default {
  data() {
    return {
      listClients: [],   // 在线的用户
      sender: "",
      receiver:"",
      offerPc: "",
      answerPc:"",
      dataChannel:"",
      shareData:new Map()
    };
  },
  async mounted() {
    // 获取本地媒体流
    let media = await navigator.mediaDevices.getUserMedia({
      video: true,
      audio: false,
    });
    console.log(media.getTracks());
    this.$refs.localPreview.srcObject = media;
    this.shareData.set("localMediaStream", media);

    // 获取远端媒体流
    let remoteStream = new MediaStream();
    this.shareData.set("remoteMediaStream", remoteStream);
    this.$refs.remotePreview.srcObject = remoteStream;
  },
  created() {
    socket.on("listClients", (data) => {
      (this.listClients = data), (this.sender = data[0]);
    });
    this.receiveOffer();
    this.receiveAnswer();
    this.receiveOfferIce();
    this.receiveAnswerOfferIce();
    this.receiveConnect()
  },
  methods: {
    // 1.发送者
    async event(receiver,sender) {
      // if(!receiver) receiver = this.listClients[1];
      this.sender = sender
      console.log('我是',sender,'点击了接受,并向',receiver,'建立连接');

      let offerPc = new RTCPeerConnection();
      this.shareData.set("offerPc", offerPc);

      // 发送ice(只要本地代理ICE 需要通过信令服务器传递信息给其他对等端时就会触发)
      offerPc.onicecandidate = (e) => {
        if (e.candidate) {
          socket.emit("offerIce", {
            receiver: receiver,
            ice: e.candidate,
          });
        }
      };

      // 把远程媒体流传入轨道中
      let remoteStream = this.shareData.get("remoteMediaStream");
      offerPc.ontrack = (e) => {
        remoteStream.addTrack(e.track);
      };

      // 把本地媒体流传入轨道中
      let localStream = this.shareData.get('localMediaStream')
      localStream.getTracks().forEach(item => {
        offerPc.addTrack(item)
      })

      // 要创建这个channel 上面的onicecandidate才会自动触发(应该放在底部,但是会不生效)
      let dataChannel = offerPc.createDataChannel("MessageChannel");
      // 发送数据
      dataChannel.onopen = (e) => {
        dataChannel.send("hello RTC");
      };
      this.shareData.set("dataChannel", dataChannel);

      // 创建并发送offer sdp给对方(sdp描述指定连接本地端的属性，包括媒体格式)
      let offer = await offerPc.createOffer();
      socket.emit("offer", {
        receiver: receiver,
        sender: this.sender,
        offer: offer,
      });
      await offerPc.setLocalDescription(new RTCSessionDescription(offer));
    },
    // 2.接收者 接收offer
    async receiveOffer() {
      socket.on("offer", async (data) => {   
        let answerPc = new RTCPeerConnection();
        let localStream = this.shareData.get("localMediaStream");
        localStream.getTracks().forEach((item) => {
          answerPc.addTrack(item);
        });
        this.shareData.set("answerPc", answerPc);

        let remoteStream = this.shareData.get("remoteMediaStream");
        answerPc.ontrack = (e) => {
          remoteStream.addTrack(e.track);
        };
        answerPc.onicecandidate = (e) => {
          
          if (e.candidate) {
            socket.emit("answerIce", {
              receiver: data.sender,
              ice: e.candidate,
            });
          }
        };

        // 接收数据
        answerPc.ondatachannel = (e) => {
          let dataChannel = e.channel;
          dataChannel.onmessage = (ev) => {
            console.log("收到消息:", ev.data);
          };
        };

        await answerPc.setRemoteDescription(
          new RTCSessionDescription(data.offer)
        );
        let answer = await answerPc.createAnswer();
        socket.emit("answer", {
          answer: answer,
          receiver: data.sender,
        });
        await answerPc.setLocalDescription(new RTCSessionDescription(answer));
      });
    },
    // 3.发送者 接收应答answer
    receiveAnswer() {
      socket.on("answer", async (data) => {
        let offerPc = this.shareData.get("offerPc");
        offerPc.setRemoteDescription(new RTCSessionDescription(data.answer));
      });
    },
    // 6.发送者 接收answerIce
    receiveAnswerOfferIce() {
      socket.on("answerIce", async (data) => {
        let offerPc = this.shareData.get('offerPc')
        
        await offerPc.addIceCandidate(new RTCIceCandidate(data.ice))
      });
    },

    // 5.接收者 接收offerIce
    receiveOfferIce() {
      socket.on("offerIce", async (data) => {
        let answerPc = this.shareData.get('answerPc')
        await answerPc.addIceCandidate(new RTCIceCandidate(data.ice))
      });
    },

    // 接收者 接收建立连接的通知
    receiveConnect(){
      socket.on("receiveConnect", (data) => {
        console.log('对方已接受邀请：',data);
        this.sender = data.receiver;
        this.receiver = data.sender
        this.event(this.sender)
      });
    }
  },
};
</script>

<style lang='less' scoped>
.videoWrap {
  height: 100%;
}
.item {
  width: 100%;
  height: 37vh;
  max-height: 260px;
  margin-bottom: 30px;
  // background-color: #000;
}
</style>
